<template>
  <div>
    <div v-if="this.$route.name == 'medicinalproductbaseEdition'" class="app-container">
      <vue-element-loading
        :active="this.$store.state.elementloading.vueElementLoading"
        spinner="spinner"
        color="#FF6700"
      />
      <el-card shadow="never">
        <el-form ref="searchForm" :inline="true" :model="searchMap" style="margin-top: 20px">
          <el-form-item prop="baseName">
            <el-input v-model="searchMap.bName" placeholder="请输入基地名称" style="width:300px">
              <template slot="prepend">基地名称</template>
            </el-input>
          </el-form-item>
          <el-form-item prop="baseArea">
            <el-select clearable v-model="searchMap.bArea" placeholder="基地面积" style="width: 150px">
              <el-option
                v-for="option in baseArea"
                :key="option.type"
                :label="option.name"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="allProduction">
            <el-select clearable v-model="searchMap.tYield" placeholder="总产量" style="width: 150px">
              <el-option
                v-for="option in allProduction"
                :key="option.type"
                :label="option.name"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="medicineValue">
            <el-input v-model="searchMap.tMedicinalQuality" placeholder style="width:250px">
              <template slot="prepend">药材质量</template>
            </el-input>
          </el-form-item>

          <el-form-item prop="medicineValue">
            <el-input v-model="searchMap.bInputLocation" placeholder style="width:300px">
              <template slot="prepend">基地地址</template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <div id="distpicker-warpper">
              <v-distpicker
                id="select-dis"
                :province="searchMap.province"
                :city="searchMap.city"
                :area="searchMap.area"
                @selected="onSelected"
                @province="handleProvince"
                @city="handleCity"
                @area="handleArea"
              ></v-distpicker>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button @click="searchBase" icon="el-icon-search"></el-button>
            <el-button type="primary" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="list"
          max-height="450"
          border
          style="width: 100%"
          highlight-current-row
          @current-change="handleSelectionChange"
          @row-click="chooseone"
        >
          <el-table-column fixed width="55">
            <template slot-scope="scope">
              <el-radio v-model="radio" :label="scope.row.id">
                <span class="el-radio__label"></span>
              </el-radio>
            </template>
          </el-table-column>
          <!-- type="index"获取索引值，labal显示标题，prop 数据字段名 -->
          <el-table-column fixed prop="eTime" label="版本时间" width="100px"></el-table-column>
          <el-table-column fixed prop="bName" label="基地名称" width="200px"></el-table-column>
          <el-table-column prop="bArea" label="基地面积"></el-table-column>
          <el-table-column prop="bPosition" label="位置信息"></el-table-column>
          <el-table-column prop="environment" label="生态环境">
            <template slot-scope="scope">
              <el-button @click="openenvironment(scope.row)" size="mini" type="primary">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="areaPhoto" label="基地照片">
            <template slot-scope="scope">
              <el-button @click="openbasephoto(scope.row)" size="mini" type="danger">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="company" label="所属公司">
            <template slot-scope="scope">
              <el-button @click="openCompany(scope.row)" size="mini" type="primary">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="gpsPosition" label="Gps位置">
            <template slot-scope="scope">
              <el-button size="mini" @click="showgps(scope.row)" type="primary">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="tCultivatedArea" label="栽培面积（亩）" width="120px"></el-table-column>
          <el-table-column prop="tReportableArea" label="可采收面积（亩）" width="140px"></el-table-column>
          <el-table-column prop="tYield" label="总产量（kg/年）" width="130px"></el-table-column>
          <el-table-column prop="medicineValue" label="药材质量">
            <template slot-scope="scope">
              <el-button @click="openmedicineValue(scope.row)" size="mini" type="danger">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="materialDirect" label="原料去向">
            <template slot-scope="scope">
              <el-button @click="toMedicinalGoneEdition(scope.row)" size="mini" type="primary">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="tPrice" label="价格/流通" width="110px"></el-table-column>
          <el-table-column prop="tBreedMode" label="种繁模式"></el-table-column>
          <el-table-column prop="tEnvironment" label="种植环境"></el-table-column>
          <el-table-column prop="tFertilizeMethod" label="施肥方法"></el-table-column>
          <el-table-column prop="tPestsPrecaution" label="病虫害防法" width="110px"></el-table-column>
          <el-table-column prop="tCollecteTime" label="采收时间"></el-table-column>
          <el-table-column prop="tCollecteMethod" label="采收方法"></el-table-column>
          <el-table-column prop="tPart" label="药用部位"></el-table-column>
          <el-table-column prop="tTotally" label="净制"></el-table-column>
          <el-table-column prop="tProcess" label="产地加工方法" width="130px"></el-table-column>
          <el-table-column prop="tProportion" label="干/鲜比"></el-table-column>
          <el-table-column prop="tScale" label="分级与包装" width="130px"></el-table-column>
          <el-table-column prop="tSampleNum" label="取样量及编号" width="130px"></el-table-column>
          <el-table-column fixed="right" prop="tPlantNum" label="植物标本编号" width="130px"></el-table-column>
        </el-table>

        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 25]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-card>

      <!-- gps弹窗 
      @ready="mapReady"
      -->
      <el-dialog v-dialogDrag width="500px" title="Gps位置" :visible.sync="locDialog">
        <template>
          <baidu-map
            class="bm-view"
            :center="center"
            :zoom="zoom"
            :scroll-wheel-zoom="true"
            ak="IGv3m1D92jWLXobdMPUyfY5hCD5j34Oz"
            ref="myMap"
            @click="getClickInfo"
            @row-click="chooseone"
          >
            <bm-scale></bm-scale>
          </baidu-map>
        </template>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="closemapdialog">关 闭</el-button>
          <!-- <el-button type="primary" @click="addData('pojoForm')">确 定</el-button> -->
        </div>
      </el-dialog>

      <!-- 药材质量弹窗 -->
      <el-dialog
        v-dialogDrag
        style="font-family:'微软雅黑'"
        title="药材质量"
        :visible.sync="dialogmedicineValue"
      >
        <mdvalue-form :path="path" :mdvalueformData="mdValueform"></mdvalue-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogmedicineValue = false">关 闭</el-button>
        </div>
      </el-dialog>

      <!-- 所属公司弹窗 -->
      <el-dialog
        v-dialogDrag
        style="font-family:'微软雅黑'"
        title="所属公司"
        :visible.sync="dialogCompanyForm"
      >
        <company-form :companyformData="companyform"></company-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogCompanyForm = false">关 闭</el-button>
        </div>
      </el-dialog>

      <!-- 生态环境弹窗 -->
      <el-dialog
        v-dialogDrag
        style="font-family:'微软雅黑'"
        title="环境详情"
        :visible.sync="dialogEnviroForm"
      >
        <environment-form :enviroformData="enviroform"></environment-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogEnviroForm = false">关 闭</el-button>
        </div>
      </el-dialog>

      <!-- 基地照片弹窗 -->
      <el-dialog
        v-dialogDrag
        title="基地照片"
        :visible.sync="dialogbaseArea"
        width="700px"
        :lock-scroll="true"
      >
        <template>
          <el-row :guntter="0">
            <vue-element-loading
              :active="this.$store.state.elementloading.imgLoading"
              spinner="spinner"
              color="#FF6700"
            />
            <el-col :span="6" class="block" v-for="(img,index) in imgs" :key="index">
              <el-image
                style="width: 180px;height: 200px"
                :src="BASEURL + path + '/' + img.tImgId"
                :fit="fit"
                lazy
              ></el-image>
            </el-col>
          </el-row>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="closeImgs">关 闭</el-button>
          </div>
        </template>
        <!-- <span slot="footer" class="dialog-footer"></span> -->
      </el-dialog>
    </div>
    <router-view />
  </div>
</template>

<script>
import MdvalueForm from "./form/mdValueEditionForm";
import EnvironmentForm from "./form/environmentEditionForm";
import CompanyForm from "./form/companyEditionForm";
import productbaseEditionApi from "@/api/productbaseEdition";
import medicinalproductbaseEditionApi from '@/api/medicinalproductbaseEdition'
import VDistpicker from "v-distpicker";
import VueElementLoading from "vue-element-loading";

// 基地面积
const baseArea = [
  { type: "1", name: "≥100亩", value: "100" },
  { type: "2", name: "≥500亩", value: "500" },
  { type: "3", name: "≥1000亩", value: "1000" },
  { type: "4", name: "≥5000亩", value: "5000" },
  { type: "5", name: "≥10000亩", value: "10000" }
];

// 总产量
const allProduction = [
  { type: "1", name: "≥100kg", value: "100" },
  { type: "2", name: "≥500kg", value: "500" },
  { type: "3", name: "≥1000kg", value: "1000" },
  { type: "4", name: "≥5000kg", value: "5000" },
  { type: "5", name: "≥10000kg", value: "10000" }
];

const BASEURL = "https://image.zysuyuan.cn:8031/";

export default {
  components: {
    MdvalueForm,
    EnvironmentForm,
    CompanyForm,
    VDistpicker,
    VueElementLoading
  },

  data() {
    return {
      enviroform: {
        bWaterEnvironment: "",
        bSoilEnvironment: "",
        bAirEnvironment: "",
        bTotalityAppraise: ""
      },
      companyform: {
        companyName: "",
        companyPosition: "",
        companyPerson: "",
        companyContact: "",
        companyMedicinal: "",
        companyRemarks: ""
      },
      mdValueform: {
        tMedicinalSharp: "", // 性状
        tMedicinalSharpImgPath: "", // 性状图片
        tMedicinalIdentify: "", // 鉴别
        tMedicinalIdentifyImgPath: "", // 鉴别图片
        tMedicinalExtractum: "", // 浸出物
        tMedicinalContentsCheck: "", // 含量测定
        tMedicinalFeatureImgPath: "", // 特征图谱或指纹图谱
        tMedicinalFeatureImgInfo: "", // 图谱说明
        tMedicinalQuality: "" // 总评
      },
      // 百度地图
      center: { lng: 0, lat: 0 },
      zoom: 3,
      // 调整装备
      locData: {
        ids: 0, //设置定位id
        longitude: "", //设置定位经度
        latitude: "" //设置定位纬度
      },
      radio: null,
      list: [],
      total: 0, //总记录数
      currentPage: 1, //当前页码
      pageSize: 5, // 每页显示10条数据
      searchMap: {
        id: "",
        page: "",
        size: "",
        bName: "",
        bArea: "",
        tYield: "",
        tMedicinalQuality: "",
        bInputLocation: "",
        bProvinceSeek: "", // 省
        bCitySeek: "", //市
        bRegionSeek: "", //区
        province: "",
        city: "",
        area: "",
        eTime: ""
      }, // 条件查询绑定的条件值
      province: null,
      city: null,
      area: null,
      allProduction,
      baseArea,
      formLabelWidth: "120px",
      maplocation: {
        // 百度地图经纬度
        latitude: "", // 维度
        longitude: "" // 经度
      },
      locDialog: false, //gps弹窗
      dialogEnviroForm: false, //生态环境弹窗
      dialogCompanyForm: false, //公司详情弹窗
      dialogmedicineValue: false, //药材质量弹窗
      dialogbaseArea: false,
      BASEURL,
      imgs: [], //基地照片
      fit: "contain",
      path: ""
    };
  },

  created() {
    this.path = localStorage.getItem("imgPath")
    this.fetchData();
  },

  watch: {
    $route(to, from) {
      // 时刻监听imgPath的值, 因为页面经过缓存，如果不进行监听，图片基础路径将不改变，会出现图片无法显示的情况
      this.path = localStorage.getItem("imgPath")
      this.fetchData();
    }
  },

  mounted() {
    setTimeout(() => {
      this.handleChangeDis();
    }, 10);
  },

  methods: {
    fetchData() {
      this.searchMap.id = localStorage.getItem("eid");
      this.searchMap.page = this.currentPage;
      this.searchMap.size = this.pageSize;
      this.searchMap.eTime = localStorage.getItem("eTime");
      var vm = this.$store;
      vm.commit("updateLoading", true);
      console.log(
        "是否开启加载",
        this.$store.state.elementloading.vueElementLoading
      );
      medicinalproductbaseEditionApi.select(this.searchMap).then(resp => {
        this.list = resp.data.rows;
        // this.radio = this.list[0].id;
        // this.maplocation.latitude = this.list[0].bLatitude;
        // this.maplocation.longitude = this.list[0].bLongitude;
        console.log("查询成功:", resp.data);
        // console.log(this.radio);
        this.total = resp.data.total;
        if (resp.data.rows) {
          vm.commit("updateLoading", false);
          console.log(
            "是否开启加载",
            this.$store.state.elementloading.vueElementLoading
          );
        }
      });
    },
    // 绑定查询按钮
    searchBase() {
      this.currentPage = 1;
      // console.log(this.searchMap);
      this.fetchData();
    },
    /************************/
    // 操作表格
    // 点击一行
    chooseone(row) {
      this.radio = row.id;
      this.backup = this.fpojo = row;
      this.maplocation.latitude = row.bLatitude;
      this.maplocation.longitude = row.bLongitude;
    },
    handleSelectionChange(row) {
      console.log(row);
      this.currentSelectItem = row;
    },
    // 当每页显示条数改变后，被触发，val是最新的显示条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.fetchData();
    },
    // 当页码改变后，被触发，val是最新的页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.fetchData();
    },
    // 重置
    reset() {
      this.searchMap = {};
    },

    // 三级地址
    handleChangeDis() {
      if (
        this.$route.name == "medicinalEdition" ||
        this.$route.name == "medicinalproductbaseEdition"
      ) {
        let selectFirst = document.getElementById("distpicker-warpper");
        let selectAll = document
          .getElementById("distpicker-warpper")
          .getElementsByTagName("select");
        // selectAll[1].style.color =  '#c0c4cc';
        for (var a = 0; a < selectAll.length; a++) {
          var selectEle = selectAll[a];
          selectEle.style.color = "#c0c4cc"; // 文字颜色
          // document.getElementById('select-dis').getElementsByTagName('select')[1][0].style.color = '#c0c4cc';
          // document.getElementById('select-dis').getElementsByTagName('select')[1][0].style.color = '#c0c4cc';
          selectEle.style.borderColor = "#d9d9d9"; // 边框颜色
        }
      }
    },
    // 获取省市区的值
    handleProvince(data) {
      // 修改选中文字颜色
      // document.getElementById('distpicker-warpper').getElementsByTagName('select')[0].style.color = '#606266';
      document.getElementById("select-dis").firstChild.style.color = "#606266";
      // 赋值给变量
      this.searchMap.bProvinceSeek = data.value.slice(0, data.value.length - 1);
      this.searchMap.province = data.value;
      if (this.searchMap.bProvinceSeek == "省") {
        this.searchMap.bProvinceSeek = "";
      }
      console.log("省：" + this.searchMap.bProvinceSeek);
    },
    handleCity(data) {
      // 修改选中文字颜色
      document
        .getElementById("select-dis")
        .getElementsByTagName("select")[1].style.color = "#606266";
      // 赋值给变量
      this.searchMap.bCitySeek = data.value.slice(0, data.value.length - 1);
      this.searchMap.city = data.value;
      if (this.searchMap.bCitySeek == "市") {
        this.searchMap.bCitySeek = "";
      }
      console.log("市：" + this.searchMap.bCitySeek);
    },
    handleArea(data) {
      // 修改选中文字颜色
      document
        .getElementById("select-dis")
        .getElementsByTagName("select")[2].style.color = "#606266";
      // 赋值给变量
      this.searchMap.bRegionSeek = data.value.slice(0, data.value.length - 1);
      this.searchMap.region = data.value;
      if (this.searchMap.bRegionSeek == "区") {
        this.searchMap.bRegionSeek = "";
      }
      console.log("区：" + this.searchMap.bRegionSeek);
    },
    onSelected(data) {
      if (data.province.code == undefined) {
        data.province.value = "";
      }
      if (data.city.code == undefined) {
        data.city.value = "";
      }
      if (data.area.code == undefined) {
        data.area.value = "";
      }
      // alert(data.province.value + ' | ' + data.city.value + ' | ' + data.area.value);
      console.log(
        data.province.value + " | " + data.city.value + " | " + data.area.value
      );
      console.log(data);
    },

    /********各种弹窗*********/
    showgps(row) {
      console.log(row);
      // 这里不能使用this.maplocation对center的经纬度赋值，因为触发按钮时，this.maplocation的值还没变，还是上一次点击行赋的值
      // 这时候需要绑定行，即点击按钮时，获取当前行的数据，再将当前行的经纬度值赋值给center
      this.center.lng = row.bLongitude;
      this.center.lat = row.bLatitude;
      console.log("经度:" + this.center.lng);
      console.log("纬度:" + this.center.lat);
      this.locDialog = true;
      this.zoom = 15;
      this.$nextTick(() => {
        // this.zoom = 15;
      });
    },
    // 百度地图方法
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      var i = 0;
      var valLen = val.length;

      if (valLen == 0) {
        this.locData.ids = 0;
      } else {
        for (i; i < valLen; i++) {
          if (i == 0) {
            this.locData.ids = val[i].id;
          } else if (i > 0) {
            this.locData.ids += "," + val[i].id;
          }
        }
      }
    },
    // 百度地图
    mapReady({ BMap, map }) {
      // this.center.lng = this.maplocation.longitude;
      // this.center.lat = this.maplocation.latitude;
      this.zoom = 15;
      window.map = map; //将map变量存储在全局
    },
    // 关闭百度地图
    closemapdialog() {
      // map.clearOverlays();
      this.locDialog = false;
    },
    // 地图点击事件
    getClickInfo(e) {
      map.clearOverlays();
      var myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat));
      map.addOverlay(myMarker);
      this.locData.longitude = e.point.lng;
      this.locData.latitude = e.point.lat;
    },

    // 弹出生态环境
    openenvironment(row) {
      this.enviroform.bWaterEnvironment = row.bWaterEnvironment;
      this.enviroform.bSoilEnvironment = row.bSoilEnvironment;
      this.enviroform.bAirEnvironment = row.bAirEnvironment;
      this.enviroform.bTotalityAppraise = row.bTotalityAppraise;
      this.dialogEnviroForm = true;
    },

    // 弹出公司详情
    openCompany(row) {
      this.companyform.companyName = row.bCompanyName;
      this.companyform.companyPosition = row.bCompanyPosition;
      this.companyform.companyPerson = row.bCompanyPerson;
      this.companyform.companyContact = row.bCompanyContact;
      this.companyform.companyMedicinal = row.bCompanyMedicinal;
      this.companyform.companyRemarks = row.bCompanyRemarks;
      this.dialogCompanyForm = true;
    },

    // 弹出药品质量
    openmedicineValue(row) {
      (this.mdValueform.tMedicinalSharp = row.tMedicinalSharp), // 性状
        (this.mdValueform.tMedicinalSharpImgPath = row.tMedicinalSharpImgPath), // 性状图片
        (this.mdValueform.tMedicinalIdentify = row.tMedicinalIdentify), // 鉴别
        (this.mdValueform.tMedicinalIdentifyImgPath =
          row.tMedicinalIdentifyImgPath), // 鉴别图片
        (this.mdValueform.tMedicinalExtractum = row.tMedicinalExtractum), // 浸出物
        (this.mdValueform.tMedicinalContentsCheck =
          row.tMedicinalContentsCheck), // 含量测定
        (this.mdValueform.tMedicinalFeatureImgPath =
          row.tMedicinalFeatureImgPath), // 特征图谱或指纹图谱
        (this.mdValueform.tMedicinalFeatureImgInfo =
          row.tMedicinalFeatureImgInfo), // 图谱说明
        (this.mdValueform.tMedicinalQuality = row.tMedicinalQuality); // 总评
      // 鉴定图片
      console.log(this.mdValueform.tMedicinalIdentifyImgPath);
      this.dialogmedicineValue = true;
    },
    // 跳转到原料去向
    toMedicinalGoneEdition(row) {
      // 存储药材id和基地id
      localStorage.setItem("tMedicinalEditionId", row.tMedicinalId);
      localStorage.setItem("tProductBaseEditionId", row.tProductBaseId);
      this.$router.push({
        name: "medicinalgoneEdition"
      });
    },
    // 查看基地照片
    openbasephoto(row) {
      var vm = this.$store;
      vm.commit("updateImgLoading", true);
      console.log("是否开启加载", this.$store.state.elementloading.imgLoading);
      var pojo = {
        tProductbaseId: row.tProductBaseId,
        eTime: localStorage.getItem("eTime")
      }
      productbaseEditionApi.selectImgsList(pojo).then(resp => {
        this.imgs = resp.data.rows;
        if (resp.data.rows != null || resp.data.rows != undefined) {
          vm.commit("updateImgLoading", false);
          console.log(
            "是否开启加载",
            this.$store.state.elementloading.imgLoading
          );
        }
        console.log(this.imgs);
      });
      this.dialogbaseArea = true;
    },
    // 关闭查看基地图片弹窗
    closeImgs() {
      this.imgs = [];
      this.dialogbaseArea = false;
    }
  }
};
</script>

<style lang="css" >
.el-dialog {
  max-height: calc(100% - 200px);
  /* max-height: 600px; */
  display: flex;
  flex-direction: column;
}
.el-dialog__body {
  overflow: auto;
}
.bm-view {
  width: auto;
  height: 500px;
  max-height: 100%;
}
.block {
  width: 200px;
  height: 220px;
  margin-left: 10px;
}

</style>